package cn.lg.soar.system.general.controller;

import cn.lg.soar.common.data.dict.IDict;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.core.annotations.IdempotentByParam;
import cn.lg.soar.core.annotations.constraints.Id;
import cn.lg.soar.core.api.IResourceApi;
import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.mvc.annotations.*;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.general.entity.Dict;
import cn.lg.soar.system.general.entity.DictItem;
import cn.lg.soar.system.general.service.IDictItemService;
import cn.lg.soar.system.general.service.IDictService;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Validated
@Api(tags = "字典类型")
@RestController
@RequestMapping(ModuleConst.MODULE_NAME + "/dict")
public class DictController extends BaseController<Dict, IDictService> {

    @Override
    protected Serializable getId(Dict entity) {
        return entity.getId();
    }

    @Autowired
    private IDictItemService dictItemService;
    @Autowired
    private IResourceApi resourceApi;

    private final static String SUBJECT = "字典类型";

    @Log(value = "新增" + SUBJECT, data = "#p0", dataId = "#$r.data")
    @IdempotentByParam("#p0")
    @CreateMapping
    public HttpResult<Serializable> create(@RequestBody @Validated Dict dict) {
        return super.createResult(dict);
    }

    @UpdateMapping
    public HttpResult<Void> update(@RequestBody @Validated Dict dict) {
        return super.updateResult(dict);
    }

    @RemoveMapping
    public HttpResult<Void> remove(@RequestBody List<Long> ids) {
        service.remove(ids);
        return HttpResult.success();
    }

    @DetailMapping
    public HttpResult<Dict> detail(@Id Long id) {
        return super.detailResult(id);
    }

    @QueryMapping
    public HttpResult<PageResult<Dict>> query(PageQuery pageQuery, QueryParams params){
        return super.queryResult(pageQuery, params);
    }

    @ExportMapping
    public void exports(QueryParams params, HttpServletResponse resp){
        super.exportExcel(DictController.SUBJECT, params, resp);
    }

    @ImportMapping
    public HttpResult<Void> imports(HttpServletRequest req){
        return super.importExcel(req);
    }

    @ExistMapping
    public HttpResult<Boolean> exist(QueryParams params){
        return super.existResult(params);
    }

    @ApiOperation("清空缓存")
    @PostMapping(value = "clear-cache", name = "清空缓存")
    public HttpResult<Void> clearCache(){
        this.dictItemService.clearCache();
        return HttpResult.success();
    }

    @ApiOperation("扫描枚举生成字典")
    @PostMapping(path = "scan", name = "扫描枚举生成字典")
    public HttpResult<Void> scan(){
        List<Dict> typeList = new ArrayList<>(128);
        List<DictItem> dataList = new ArrayList<>(512);
        Set<String> codes = new HashSet<>(service.codeList());
        resourceApi.getAllSysDict()
                .forEach(v -> {
                    String code = v.getCode();
                    // 生成字典类型
                    Dict dict;
                    if (codes.contains(code)) {
                        dict = service.getOne(
                                Wrappers.<Dict>lambdaQuery()
                                        .select(Dict::getId)
                                        .eq(Dict::getCode, code)
                        );
                    } else {
                        dict = new Dict();
                        dict.setId(IdWorker.getId());
                        dict.setName(v.getName());
                        dict.setCode(code);
                        dict.setEnumerated(true);
                        typeList.add(dict);
                    }
                    // 生成字典数据
                    IDict<Integer>[] enums = v.getDicts();
                    if (enums.length == 0) {
                        return;
                    }
                    List<DictItem> list = this.dictItemService.list(
                            Wrappers.<DictItem>lambdaQuery()
                                    .select(DictItem::getValue)
                                    .eq(DictItem::getDictId, dict.getId())
                    );
                    Set<Integer> values = list.stream()
                            .map(DictItem::getValue)
                            .collect(Collectors.toSet());
                    for (IDict<Integer> e : enums) {
                        if (values.contains(e.getValue())) {
                            continue;
                        }
                        DictItem data = new DictItem();
                        data.setEnumerated(true);
                        data.setSort(e.getValue());
                        data.setValue(e.getValue());
                        data.setLabel(e.getLabel());
                        data.setDictId(dict.getId());
                        dataList.add(data);
                    }
                    list.clear();
                    values.clear();
                });
        codes.clear();
        if (!typeList.isEmpty()) {
            AssertUtil.isTrue(service.saveBatch(typeList), "生成字典类型失败");
            typeList.clear();
        }
        if (!dataList.isEmpty()) {
            AssertUtil.isTrue(dictItemService.saveBatch(dataList), "生成字典数据失败");
            dataList.clear();
        }
        return HttpResult.success();
    }

}
